package com.github.od.listener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.eureka.server.event.EurekaInstanceCanceledEvent;
import org.springframework.cloud.netflix.eureka.server.event.EurekaInstanceRegisteredEvent;
import org.springframework.cloud.netflix.eureka.server.event.EurekaInstanceRenewedEvent;
import org.springframework.cloud.netflix.eureka.server.event.EurekaRegistryAvailableEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;

import com.netflix.discovery.shared.Applications;
import com.netflix.eureka.EurekaServerContextHolder;
import com.netflix.eureka.registry.PeerAwareInstanceRegistry;

/**
 * Eureka监听器
 *
 * @author xieweikun
 * @Date 2017/11/14 9:12
 */
@Configuration
@EnableScheduling
public class EurekaInstanceCanceledListener implements ApplicationListener {

	private Logger log = LoggerFactory.getLogger(EurekaInstanceCanceledListener.class);

	@Override
	public void onApplicationEvent(ApplicationEvent applicationEvent) {
		// 服务挂掉事件
		if (applicationEvent instanceof EurekaInstanceCanceledEvent) {
			EurekaInstanceCanceledEvent event = (EurekaInstanceCanceledEvent) applicationEvent;
			// 获取当前Eureka实例当中的结点信息
			PeerAwareInstanceRegistry registry = EurekaServerContextHolder.getInstance().getServerContext()
					.getRegistry();
			Applications applications = registry.getApplications();
			// 遍历获取已注册节点中与当前失效节点ID一致的节点信息
			applications.getRegisteredApplications().forEach((registeredApplication) -> {
				registeredApplication.getInstances().forEach((instance) -> {
					if (instance.getInstanceId().equals(event.getServerId())) {
						log.info(instance.getAppName() + "服务挂啦。。。");
						// TODO 扩展消息提醒 邮件、手机短信、微信等
					}
				});
			});
		}

		// 注册事件
		if (applicationEvent instanceof EurekaInstanceRegisteredEvent) {
			EurekaInstanceRegisteredEvent event = (EurekaInstanceRegisteredEvent) applicationEvent;
			log.info(event.getInstanceInfo().getAppName() + "服务注册成功。。。");
		}

		// 心跳事件
		if (applicationEvent instanceof EurekaInstanceRenewedEvent) {
			EurekaInstanceRenewedEvent event = (EurekaInstanceRenewedEvent) applicationEvent;
			log.info("心跳监测服务：" + event.getInstanceInfo().getAppName());
		}

		// 启动事件
		if (applicationEvent instanceof EurekaRegistryAvailableEvent) {
			log.info("Eureka服务启动成功。。。");
		}
	}

}
